package com.tenebrous.jestic.controller.framwork.meber.organ;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.tenebrous.jestic.compents.annotations.Weblog;
import com.tenebrous.jestic.compents.annotations.WeblogEnum;
import com.tenebrous.jestic.controller.SupperController;
import com.tenebrous.jestic.entity.framwork.meber.organ.*;
import com.tenebrous.jestic.entity.framwork.meber.organ.*;
import com.tenebrous.jestic.entity.framwork.system.SysParams;
import com.tenebrous.jestic.mapper.idao.framwork.meber.organ.OrgUserAbnomalMapper;
import com.tenebrous.jestic.mapper.idao.framwork.meber.organ.OrgUserProcessMapper;
import com.tenebrous.jestic.service.framwork.meber.organ.OrgUserExtService;
import com.tenebrous.jestic.service.framwork.meber.organ.OrgUserGrantService;
import com.tenebrous.jestic.service.framwork.meber.organ.OrgUserService;
import com.tenebrous.jestic.service.framwork.system.SysParamsService;
import com.rain.ops.sdk.dto.ApiResult;
import com.rain.ops.sdk.utils.BeanUtils;
import com.rain.ops.sdk.utils.UUIDUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Validated
@RestController
@RequestMapping("/organ/user")
public class UserController extends SupperController {

    @Autowired
    private OrgUserService userService;

    @Autowired
    private SysParamsService paramsService;

    @Autowired
    private OrgUserGrantService grantService;

    @Autowired
    private OrgUserExtService userExtService;

    @Autowired
    private OrgUserAbnomalMapper abbnomalMapper;

    @Autowired
    private OrgUserProcessMapper orgUserProcessMapper;

    /**
     * 查找用户，包含扩展信息。
     *
     * @param id
     * @return
     */
    @PostMapping("/get")
    public ApiResult get(@NotBlank String id) {
        OrgUser ou = userService.getById(id);
        if (ou != null) {
            return new ApiResult(200, "查询成功。", ou);
        }
        return new ApiResult(999, "查询失败。");
    }

    /**
     * 加载用户记录，不包含扩展信息。
     *
     * @param id
     * @return
     */
    @PostMapping("/load")
    public ApiResult load(@NotBlank String id) {
        return new ApiResult(200, "查询成功。", userService.getById(id));
    }

    @PostMapping("/get-by-procinstid")
    public ApiResult getByProcinstid(String procinstid) {
        OrgUser ouser = super.getCurrentUser();
        OrgUser ou = userService.getById(ouser.getId());
        return new ApiResult(200, "查询成功。", ou);
    }

    /**
     * 员工信息初始化从人员流程实例中间表取数据
     *
     * @param procinstid
     * @return
     */
    @PostMapping("/getuserProcess-by-procinstid")
    public ApiResult getuserProcessByProcinstid(String procinstid) {
        OrgUserProcess item = orgUserProcessMapper.selectByPrimaryKey(procinstid);
        OrgUser currentuser = super.getCurrentUser();
        OrgUser ou = null;
        if (item != null) {
            ou = JSONObject.parseObject(item.getAuserjson(), OrgUser.class);
        } else {
            ou = userService.getById(currentuser.getId());
        }
        return new ApiResult(200, "查询成功。", ou);
    }

    @PostMapping("/account/get")
    public ApiResult getAccount(@NotBlank String userid) {
        OrgUserAccount ou = userService.getAccountById(userid);
        if (ou != null) {
            return new ApiResult(200, "查询成功。", ou);
        } else {
            return new ApiResult(999, "查询失败，未找到指定用户账号。");
        }
    }

    @PostMapping("/avatar/get")
    public ApiResult getAvatar(@NotBlank String id) {
        OrgUser ou = userService.selectByPrimaryKey(id);
        if (ou != null) {
            return new ApiResult(200, "查询成功。", ou.getAvatar());
        }
        return new ApiResult(999, "查询失败。");
    }

    @PostMapping("/state/count")
    public ApiResult stateCount(String cid, String did) {
        return new ApiResult(200, "查询成功。", userService.queryStateCount(cid, did));
    }

    @PostMapping("/estate/count")
    public ApiResult estateCount(String cid, String did) {
        return new ApiResult(200, "查询成功。", userService.queryEstateCount(cid, did));
    }

    @PostMapping("/etype/count")
    public ApiResult etypeCount(String cid, String did) {
        return new ApiResult(200, "查询成功。", userService.queryEtypeCount(cid, did));
    }

    /**
     * 用户分页查询
     *
     * @param cid         单位标识
     * @param did         部门标识
     * @param etype       人员类型（实习、试用、正式）
     * @param estate      员工状态（在职、离职、去世、离退）
     * @param politiCode  政治面貌（中共党员、中共预备党员、共青团员、民主党派、群众）
     * @param edutionCode 学历（大专、本科学士、本科双学士、硕士研究生、博士研究生）
     * @param degreeCode  学位（学士、双学士、硕士、博士、无）
     * @param sexCode     性别（男、女）
     * @param marryCode   婚姻状况（已婚、未婚）
     * @param realname    用户姓名
     * @return
     * @throws InterruptedException
     */
    @PostMapping("/paging")
    public ApiResult paging(String cid, String did, String etype, String estate, Integer dstate, String politiCode, String edutionCode, String degreeCode, String sexCode, String marryCode, String realname) {
        PageInfo<OrgUser> pageInfo = userService.queryPagingList(super.getPageIndex(), super.getPageSize(), cid, did, etype, estate, dstate, politiCode, edutionCode, degreeCode, sexCode, marryCode, realname);
        return new ApiResult(200, "查询成功。", pageInfo);
    }

    /**
     * 更新对象
     *
     * @param item
     * @return
     */
    @PostMapping("/update")
    @Weblog(description = "更新用户基本信息", method = WeblogEnum.UPDATE)
    public ApiResult update(@NotNull OrgUser item) {
        Date dt = new Date();
        OrgUser ouser = super.getCurrentUser();
        if (StringUtils.isNotBlank(item.getId())) {
            item.setUpdateDate(dt);
            userService.updateSelective(item);
        } else {
            item.setDstate(1);
            item.setCreateDate(dt);
            item.setId(UUIDUtils.randomUUID());
            userService.saveSelective(item);
            String safter = JSON.toJSONString(item);

            OrgUserAbnomal abnomal = new OrgUserAbnomal();
            abnomal.setId(UUIDUtils.randomUUID());
            abnomal.setUserid(item.getId());
            abnomal.setSevent("创建人员");
            abnomal.setAbnomalAf(safter);
            abnomal.setRemark(String.format("创建员工信息"));
            abnomal.setCreateUserid(ouser != null ? ouser.getId() : "");
            abnomal.setCreateDate(dt);
            this.abbnomalMapper.insertSelective(abnomal);
        }
        return new ApiResult(200, "更新成功。", item);
    }

    /**
     * 新人入职设置账号
     *
     * @param item
     * @return
     */
    @PostMapping("/saveuserandaccount")
    @Weblog(description = "新人入职账号设置", method = WeblogEnum.UPDATE)
    public ApiResult saveUserAndAccount(@NotNull OrgUser item) {
        OrgUser user = super.getCurrentUser();
        return userService.saveUserAndAccount(item, user);
    }

    /**
     * 修改入职员工账号
     *
     * @param item
     * @return
     */
    @PostMapping("/updateuserandaccount")
    @Weblog(description = "修改入职员工账号", method = WeblogEnum.UPDATE)
    public ApiResult updateUserAndAccount(@NotNull OrgUser item) {
        OrgUser user = super.getCurrentUser();
        ApiResult api = userService.updateUserAndAccount(item, user);
        return api;
    }

    /**
     * 更新履历表
     *
     * @param userInfo
     * @return
     */
//    @PostMapping("/info/updateprocinstid")
//    @Weblog(description = "更新履历表", method = WeblogEnum.UPDATE)
//    public ApiResult updateprocinstid(@NotNull OrgUser userInfo) {
//        OrgUser user = super.getCurrentUser();
//        return userService.updateprocinstid(userInfo, user);
//    }
//
//    /**
//     * 更新履历表 版本2
//     *
//     * @param
//     * @return
//     */
//    @PostMapping("/info/saveorguserprocess")
//    @Weblog(description = "更新履历表", method = WeblogEnum.UPDATE)
//    public ApiResult saveOrgUserProcess(String usejson, String procinstid, String uid, String stype) {
//        return userService.saveOrgUserProcess(usejson, procinstid, uid, stype);
//
//    }

    /**
     * 更新履历表
     *
     * @param userInfo
     * @return
     */
    @PostMapping("/resume/update")
    @Weblog(description = "更新履历表", method = WeblogEnum.UPDATE)
    public ApiResult updateResumeInfo(@NotNull OrgUser userInfo) {
        OrgUser user = super.getCurrentUser();
        return userService.updateResumeInfo(userInfo, user);
    }

    /**
     * 账号更新
     *
     * @param item
     * @return
     */
    @PostMapping("/account/update")
    @Weblog(description = "更新用户账号信息", method = WeblogEnum.UPDATE)
    public ApiResult updateAccount(@NotNull @Validated OrgUserAccount item) {
        OrgUser ouser = super.getCurrentUser();
        if (StringUtils.isNotBlank(item.getId())) {
            OrgUserAccount ou = userService.getAccountById(item.getId());
            if (ou != null) {
                item.setPassword(null);
                item.setUpdateDate(new Date());
                item.setUpdateUserid(ouser.getId());
                userService.updateAccountSelective(item);
            } else {
                item.setEnabled(1);
                item.setUserid(item.getId());
                item.setCreateDate(new Date());
                item.setCreateUserid(ouser.getId());
                item.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));
                userService.saveAccountSelective(item);
            }
        } else {
            return new ApiResult(999, "保存失败，未指定登陆用户。");
        }
        return new ApiResult(200, "保存成功。");
    }

    /**
     * 密码初始化
     *
     * @param ids
     * @return
     */
    @PostMapping("/account/pwd/init")
    @Weblog(description = "密码初始化", method = WeblogEnum.UPDATE)
    public ApiResult initAccountPwd(@NotEmpty String[] ids) {
        return new ApiResult(200, "初始化成功。", userService.initAccountPwd(ids));
    }

    /**
     * 更新当前登陆用户头像
     *
     * @param avatar 图片地址
     * @return
     */
    @PostMapping("/avatar/update")
    @Weblog(description = "更新用户头像地址", method = WeblogEnum.UPDATE)
    public ApiResult updatetAvatar(@NotBlank String avatar) {
        OrgUser ouser = super.getCurrentUser();
        return userService.updatetAvatar(ouser.getId(), avatar);
    }

    /**
     * 删除对象
     *
     * @param ids
     * @return
     */
    @PostMapping("/delete")
    @Weblog(description = "删除指定用户信息", method = WeblogEnum.DELETE)
    public ApiResult delete(@NotEmpty String[] ids) {
        return new ApiResult(200, "删除成功。", userService.deleteByIds(ids));
    }

    /**
     * 用户信息比对
     *
     * @param ids 用户ID集合
     * @return
     */
    @PostMapping("/compare")
    public ApiResult compare(@NotEmpty String[] ids) {
        List<OrgUser> ulist = userService.queryList(ids);
        for (OrgUser ouser : ulist) {
            List<OrgUserEducate> educatelist = userExtService.queryEducateList(ouser.getId());
            ouser.setEducatelist(educatelist);

            List<OrgUserWork> worklist = userExtService.queryWorkList(ouser.getId());
            ouser.setWorklist(worklist);

            List<OrgUserCerti> certilist = userExtService.queryCertiList(ouser.getId());
            ouser.setCertilist(certilist);

            List<OrgUserTrain> trainlist = userExtService.queryTrainList(ouser.getId());
            ouser.setTrainlist(trainlist);

            List<OrgUserFamily> familylist = userExtService.queryFamilyList(ouser.getId());
            ouser.setFamilylist(familylist);
        }
        return new ApiResult(200, "查询成功。", ulist);
    }

    /**
     * 调整单位/部门
     *
     * @param id                 被移动的人员ID
     * @param targetDepartmentid 移动后所属的部门ID
     * @return
     */
    @PostMapping("/unusual/organ")
    @Weblog(description = "调整单位/部门", method = WeblogEnum.UPDATE)
    public ApiResult unusualOrgan(@NotBlank String id, @NotBlank String targetDepartmentid) {
        OrgUser ouser = super.getCurrentUser();
        return userService.unusualOrgan(id, targetDepartmentid, ouser);
    }

    /**
     * 调整岗序岗位
     *
     * @param id                  被移动的人员ID
     * @param targetStationid
     * @param targetStationgradid
     * @return
     */
    @PostMapping("/unusual/station")
    @Weblog(description = "调整岗序岗位", method = WeblogEnum.UPDATE)
    public ApiResult unusualStation(@NotBlank String id, @NotBlank String targetStationid, @NotBlank String targetStationgradid) {
        OrgUser ouser = super.getCurrentUser();
        return userService.unusualStation(id, targetStationid, targetStationgradid, ouser);
    }

    /**
     * 调整员工类型
     *
     * @param id          被调整的人员ID
     * @param targetEtype 调整后员工类型
     * @return
     */
    @PostMapping("/unusual/etype")
    @Weblog(description = "调整员工类型", method = WeblogEnum.UPDATE)
    public ApiResult unusualEtype(@NotBlank String id, @NotBlank String targetEtype) {
        OrgUser ouser = super.getCurrentUser();
        return userService.unusualEtype(id, targetEtype, ouser);
    }

    /**
     * 调整员工状态
     *
     * @param id           调整的人员ID
     * @param targetEstate 调整后员工状态
     * @return
     */
    @PostMapping("/unusual/estate")
    @Weblog(description = "调整员工状态", method = WeblogEnum.UPDATE)
    public ApiResult unusualEstate(@NotBlank String id, @NotBlank String targetEstate) {
        OrgUser ouser = super.getCurrentUser();
        return userService.unusualEstate(id, targetEstate, ouser);
    }

    /**
     * 通讯录分页查询
     * @param realname
     * @param mobile
     * @param companyid
     * @param departmentid
     * @return
     */
    @PostMapping("/mail/paging")
    public ApiResult pagingMail(String realname, String mobile, String companyid, String departmentid) {
        PageInfo<OrgUser> pageInfo = userService.pagingMailList(super.getPageIndex(), super.getPageSize(), realname, mobile, companyid, departmentid);
        for (OrgUser user : pageInfo.getList()) {
            this.parseMailUserinfo(user);
        }
        return new ApiResult(200, "查询成功。", pageInfo);
    }

    /**
     * 分页查询指定用户授权集合
     *
     * @param userid
     * @return
     */
    @PostMapping("/grant/paging")
    public ApiResult grantPaging(@NotBlank String userid) {
        PageInfo pageInfo = grantService.pagingList(super.getPageIndex(), super.getPageSize(), userid);
        return new ApiResult(200, "查询成功。", pageInfo);
    }

    /**
     * 更新指定用戶授权
     *
     * @param userid
     * @param targets
     * @return
     */
    @PostMapping("/grant/update")
    public ApiResult updateGrant(@NotBlank String userid, @NotBlank String targets) {
        int cnt = grantService.updateGrant(userid, targets);
        return new ApiResult(200, String.format("授权完成，成功添加%d条授权记录。", cnt));
    }

    /**
     * 更新指定用户属性授权
     *
     * @param id
     * @param scopes
     * @return
     */
    @PostMapping("/grant/scope/update")
    public ApiResult updateGrantScope(@NotBlank String id, String[] scopes) {
        return new ApiResult(200, "更新成功。", grantService.updateGrantScope(id, scopes));
    }

    /**
     * 删除授权
     *
     * @param ids
     * @return
     */
    @PostMapping("/grant/delete")
    public ApiResult deleteGrant(@NotEmpty String[] ids) {
        return new ApiResult(200, "删除成功。", grantService.deleteByIds(ids));
    }

    /**
     * 检查是否有权限查看用户信息
     *
     * @param targetUserid 被查看的用户ID
     * @return
     */
    @PostMapping("/grant/check")
    public ApiResult checkacl(@NotBlank String targetUserid) {
        List<String> scoplist = new ArrayList<>();
        OrgUser ouser = super.getCurrentUser();
        OrgUser tuser = this.userService.getById(targetUserid);
        if (tuser != null) {
            String[] targetids = new String[]{tuser.getId(), tuser.getDepartmentid(), tuser.getCompanyid()};
            List<String> slist = this.grantService.checkGrant(ouser.getId(), targetids);
            if (slist.size() > 0) {
                return new ApiResult(200, "验证ACL成功。", slist);
            } else {
                return new ApiResult(999, "验证ACL失败，未授予的查看权限。");
            }
        } else {
            return new ApiResult(999, "验证ACL失败，查看的用户不存在。");
        }
    }

    /**
     * 查询异动记录
     *
     * @return
     */
    @PostMapping("/abnomal/query")
    public ApiResult queryAbnomal(@NotBlank String userid) {
        List<OrgUserAbnomal> alist = userService.queryAbnomalList(userid);
        return new ApiResult(200, "查询成功。", alist);
    }

    private void parseMailUserinfo(OrgUser user) {
        List<SysParams> list = paramsService.queryParamsBySkey("setting.mail.user.props", user.getId());
        if (list.size() > 0) {
            String svalue = list.get(0).getSvalue();
            if (StringUtils.isNotBlank(svalue)) {
                JSONArray jsonArray = JSONArray.parseArray(svalue);
                for (Object object : jsonArray) {
                    JSONObject jsonObject = (JSONObject) object;
                    String key = jsonObject.getString("key");
                    Boolean showed = jsonObject.getBoolean("showed");
                    if (showed != null && !showed) {
                        BeanUtils.setFieldValueByFieldName(key, "***", user);
                    }
                }
            }
        }
    }

//    @GetMapping("/get/user/list")
//    public ApiResult getUserList(String noticeId) {
//        return new ApiResult(200, "查询成功。", userService.getUserList(noticeId));
//    }

}
